package com.pp.common.filter;

import com.pp.common.util.JwtUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * JWT 验证过滤器
 * 每一次请求过来都会通过一次 JwtAuthenticationFilter 过滤器
 */
@WebFilter(filterName = "JwtAuthenticationFilter")
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    /**
     * 受保护的资源
     */
    private static List<String> protectedPaths;

    private static final PathMatcher pathMatcher = new AntPathMatcher();

    static {
        initPatternPaths();
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.out.println("----- 过滤之前的 Request Header: " + request.getHeader("Authorization"));
        try {
            // 若是受保护的请求 (即需要提供 token 才能访问的请求)，需要校验 token 的有效性，校验通过才能放行到 Controller
            if(isProtectedPath(request)) {
                if(!request.getMethod().equals("OPTIONS"))
                    request = JwtUtils.validateTokenAndAddUserIdToHeader(request);
                    System.out.println("Request after being filtered" + request.getHeader("username"));
            }
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
            return;
        }

        // token 验证通过后，放行当前 request 对象到 SpringMVC 的 Controller
        filterChain.doFilter(request, response);
    }

    /**
     * 判断是否是受保护的资源
     */
    private static boolean isProtectedPath(HttpServletRequest request) {
        boolean isMatched = false;
        for( String passedPath : protectedPaths) {
            isMatched = pathMatcher.match(passedPath, request.getServletPath());
            if( isMatched ) {
                break;
            }
        }
        return isMatched;
    }

    /**
     * 初始化受保护的资源
     */
    // TODO 随时需要修改
    private static void initPatternPaths() {
        protectedPaths = new ArrayList<>();
        protectedPaths.add("/api/user/info");
        protectedPaths.add("/api/user/update");
        protectedPaths.add("/api/post/create");
        protectedPaths.add("/api/post/update");
        protectedPaths.add("/api/post/delete/*");
        protectedPaths.add("/api/comment/create");
        protectedPaths.add("/api/relationship/subscribe/*");
        protectedPaths.add("/api/relationship/unsubscribe/*");
        protectedPaths.add("/api/relationship/validate/*");
    }

}
